﻿
using WXY.Course.Common.Authorization;
using WXY.Course.Common.MVCExtension;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WXY.Course.Web.Areas.Admin.Filter;
using WXY.Course.Model;
using WXY.Course.BLL;
using WXY.Course.Web.Areas.Admin.Models;

namespace WXY.Course.Web.Areas.Admin.Controllers
{
    public class AccountController : Controller
    {
        private AccountBLL _accountBLL = new AccountBLL();

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(string userName, string password, string returnUrl)
        {
            string message = string.Empty;
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("", "参数错误");
                return View();
            }

            var userInfo = _accountBLL.Get(userName, password);
            if (userInfo == null)
            {
                ModelState.AddModelError("", "用户名或密码错误");
                return View();
            }
            AdminContext.Login(userInfo);
            return Redirect(GetReferURL());
        }

        [DefaultAuthorize]
        public ActionResult UserDetail()
        {
            UserInfo userInfo = HttpContext.Items["UserInfo"] as UserInfo;
            return View(userInfo);
        }

        [DefaultAuthorize]
        public ActionResult UserList(int? page, string userName, DateTime? beginTime, DateTime? endTime)
        {
            if (!page.HasValue) page = 1;

            UserInfo userInfo = HttpContext.Items["UserInfo"] as UserInfo;

            ViewData["UserInfo"] = userInfo;
            PageParams pageParams = new PageParams
            {
                PageIndex = page.Value,
                PageSize = 10,
                BeginTime = beginTime,
                EndTime = endTime,
                IsNeedRecordCount = true
            };

            var list = _accountBLL.GetList(pageParams);

            PageViewModel<UserInfo> pageViewModel = new PageViewModel<UserInfo>();

            pageViewModel.Value = list;
            pageViewModel.PageInfo = PageInfo.Create(pageParams.PageIndex, pageParams.PageSize);
            pageViewModel.PageInfo.RecordCount = pageParams.RecordCount;

            return View(pageViewModel);
        }

        [HttpPost]
        [DefaultAuthorize]
        [JsonExceptionFilter(typeof(AccountController))]
        public JsonResult Delete(int id)
        {
            int result = 0;
            string message = "";

            UserInfo userInfo = HttpContext.Items["UserInfo"] as UserInfo;

            UserInfo delUser = _accountBLL.Get(id);
            if (delUser.CreateUser == null || delUser.CreateUser.Code != userInfo.Code)
            {
                message = "无权删除的用户";
            }
            else
            {
                result = _accountBLL.Delete(id);
            }
            return Json(new { IsSuccess = result > 0, Value = result, Message = message });
        }

        public ViewResult UserEdit(int? id)
        {
            var info = new UserInfo();
            if (id.HasValue)
            {
                info = _accountBLL.Get(id.Value);
            }
            return View(info);
        }

        [HttpPost]
        [DefaultAuthorize]
        public ActionResult UserEdit(UserInfo info)
        {
            if (!ModelState.IsValid)
            {
                return View(info);
            }

            bool successed = false;
            UserInfo userInfo = HttpContext.Items["UserInfo"] as UserInfo;
            info.CreateUser = userInfo;
            if (info.Code.HasValue)
            {
                successed = _accountBLL.Update(info) > 0;
            }
            else
            {
                successed = _accountBLL.Insert(info) > 0;
            }
            if (!successed)
            {
                ModelState.AddModelError(string.Empty, "操作失败");
                return View(info);
            }
            return RedirectToAction("UserList");
        }

        [DefaultAuthorize]
        public ActionResult UpdatePass()
        {
            return View();
        }

        [HttpPost]
        public JsonResult UpdatePass(string oldPassword, string password)
        {
            UserInfo userInfo = HttpContext.Items["UserInfo"] as UserInfo;

            if (!userInfo.Password.Equals(oldPassword))
            {
                return Json(new BoolResult { IsSuccess = false, Message = "旧密码输入错误" });
            }

            bool updateResult = _accountBLL.UpdatePass(1, password) > 0;
            if (!updateResult)
            {
                return Json(new BoolResult { IsSuccess = false, Message = "修改失败" });
            }
            return Json(new BoolResult { IsSuccess = true });
        }

        [HttpPost]
        public void LogOut()
        {
            AdminContext.LogOut();
        }

        private string GetReferURL()
        {
            Uri uri = null;
            if (Uri.TryCreate(this.Request["ReturnUrl"], UriKind.RelativeOrAbsolute, out uri))
            {
                string newUri = uri.ToString();
                return string.IsNullOrEmpty(newUri) ? "/Admin" : newUri;
            }

            if (this.Request.UrlReferrer != null)
            {
                if (this.Request.PhysicalPath.Equals(this.Request.UrlReferrer))
                {
                    return this.Request.UrlReferrer.ToString();
                }
            }
            return "/Admin";
        }
    }
}



